package start.demo01.StringAnalysis;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class ScopeMatcher {
    private static final Set<String> SCOPE_SET;
    static {
        SCOPE_SET = new HashSet<>();
        SCOPE_SET.add("user:*");
        SCOPE_SET.add("*:read");
        SCOPE_SET.add("*admin*");
        SCOPE_SET.add("foo");
    }
    /*
        初始化时把每个 pattern → 一个 Predicate
     */
    private static final List<Predicate<String>> MATCHERS =
        SCOPE_SET.stream()
                 .map(ScopeMatcher::toPredicate)
                 .collect(Collectors.toList());

    public static boolean isScopeMatched(String scope) {
        return MATCHERS.stream().anyMatch(p -> p.test(scope));
    }

    private static Predicate<String> toPredicate(String pattern) {
        if (!pattern.contains("*")) {
            return scope -> scope.equals(pattern);
        }
        if (pattern.startsWith("*") && pattern.endsWith("*")) {
            return scope -> scope.contains(pattern.substring(1, pattern.length() - 1));
        }
        if (pattern.startsWith("*")) {
            return scope -> scope.endsWith(pattern.substring(1));
        }
        // pattern.endsWith("*")
        return scope -> scope.startsWith(pattern.substring(0, pattern.length() - 1));
    }

    // 测试
    public static void main(String[] args) {
        List<String> tests = Arrays.asList("user:create", "admin:read", "superadmin", "foo", "guest");
        tests.forEach(s ->System.out.printf("%-12s -> %b%n", s, isScopeMatched(s)));
    }
}
